/*
Copyright (c) 2009, David A. Freels Sr.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package net.whippetcode.plugins.intellij.hudson.parser;

import net.whippetcode.plugins.intellij.hudson.job.IJobHandler;
import net.whippetcode.plugins.intellij.hudson.job.Job;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class acts as a SaxParser Handler and processes Job objects.
 *
 * @author David A. Freels Sr.
 */
public class HudsonJobHandler extends DefaultHandler
{
	private static final Map<String, ITagCommand> commands = new HashMap<String, ITagCommand>();
	private static final String HUDSON = "hudson";
	private static final String LISTVIEW = "listView";

	private Job currentJob;
	private ITagCommand currentCommand;
	private StringBuilder currentCommandName = new StringBuilder();
	private List<IJobHandler> handlers = new ArrayList<IJobHandler>();
	private JobPropertyBuilder builder;

	public HudsonJobHandler(String serverAddress)
	{
		builder = new JobPropertyBuilder(serverAddress);
	}

	static
	{
		commands.clear();
		commands.put("name", new NameTagCommand());
		commands.put("color", new ColorTagCommand());
		commands.put("inQueue", new QueueTagCommand());
        commands.put("/lastSuccessfulBuild/number", new LastSuccessfulRevisionTagCommand());
        commands.put("/lastFailedBuild/number", new LastFailedRevisionTagCommand());
        commands.put("/lastStableBuild/number", new LastStableRevisionTagCommand());
	}

	@Override
	public void endDocument() throws SAXException
	{
		super.endDocument();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
	{
		if (HUDSON.equals(qName) ||
			 LISTVIEW.equals(qName))
		{
			return;
		}

		if ("job".equals(qName) && currentCommandName.length() == 0)
		{
			currentJob = new Job();
		}
		else
		{
			if (!commands.containsKey(qName) &&
				 !commands.containsKey(currentCommandName.toString()))
			{
				currentCommandName.append("/").append(qName);
			}

			if (currentCommandName.length() == 0 && commands.containsKey(qName))
			{
				currentCommand = commands.get(qName);
			}
			else if (commands.containsKey(currentCommandName.toString()))
			{
				currentCommand = commands.get(currentCommandName.toString());
			}
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException
	{
		if (currentCommand != null && currentJob != null)
		{
			currentCommand.processText(new String(ch, start, length), currentJob);
			currentCommand = null;
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException
	{
		if ("job".equals(qName) && currentCommandName.length() == 0 && currentJob != null)
		{
			builder.populateJob(currentJob);

			for (IJobHandler handler : handlers)
			{
				handler.handleJob(currentJob);
			}
			currentJob = null;
		}

		if (!commands.containsKey(qName) && currentCommandName.indexOf("/" + qName) != -1)
		{
			int index = currentCommandName.indexOf("/" + qName);
			currentCommandName.delete(index, (index + qName.length() + 1));
		}
	}

    /**
     * Register a new IJobHandler.
     *
     * @param handler The IJobHandler.
     */
	public void addJobHandler(IJobHandler handler)
	{
		handlers.add(handler);
	}

    /**
     * Unregister a IJobhandler.
     *
     * @param handler The IJobHandler to unregister.
     */
	public void removeJobHandler(IJobHandler handler)
	{
		handlers.remove(handler);
	}

    /**
     * Resets the statte of this class and any registered IJobHandlers.
     */
    public void reset()
    {
        for (IJobHandler handler : handlers)
        {
            handler.reset();
        }
    }
}
